package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.*;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        // 1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        // 2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            // 账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5DigestAsHex.equals(employee.getPassword())) {
            // 密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            // 账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        // 3、返回实体对象
        return employee;
    }

    @Override
    public void create(EmployeeDTO employeeDTO) {
        // 1. 参数的校验 - 需求文档（原型）
        // 账号输入不符，请输入3-20个字符
        checkParams(employeeDTO);
        // 2. 核心代码输出
        Employee employee = new Employee();
        // 对应类型的属性 值  copy过来
        BeanUtils.copyProperties(employeeDTO, employee);
        // 添加员工 默认密码123456
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(md5DigestAsHex);
        employee.setStatus(StatusConstant.ENABLE);
        employeeMapper.insert(employee);
    }

    @Override
    public PageResult<Employee> page(EmployeePageQueryDTO employeePageQueryDTO) {
        // 1. 开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        // 2. 原始查询
        Employee employeeQuery = new Employee();
        employeeQuery.setName(employeePageQueryDTO.getName());
        Page<Employee> employeePage = employeeMapper.selectPage(employeeQuery);
        // 3. 提取需要的值
        long total = employeePage.getTotal();
        List<Employee> result = employeePage.getResult();
        // 分页查询
        PageResult<Employee> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setRecords(result);
        return pageResult;
    }

    @Override
    public void modifyStatus(Long id, Integer status) {
        Employee employee = new Employee();
        employee.setId(id);
        employee.setStatus(status);
        employeeMapper.updateById(employee);
    }

    @Override
    public Employee queryById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword(null);
        return employee;
    }

    @Override
    public void modifyById(EmployeeDTO employeeDTO) {
        // 参数校验
        checkParams(employeeDTO);
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        // employee.setUpdateTime(LocalDateTime.now());
        // employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateById(employee);
    }

    /**
     * 参数校验
     *
     * @param employeeDTO
     */
    private void checkParams(EmployeeDTO employeeDTO) {
        if (Objects.isNull(employeeDTO.getUsername()) ||
                employeeDTO.getUsername().length() < 3 ||
                employeeDTO.getUsername().length() > 20) {
            throw new AccountFormatException("账号输入不符，请输入3-20个字符");
        }
        // 账号重复，请调整 通过数量判断是否存在
        Integer countByUsername = 0;
        if (Objects.isNull(employeeDTO.getId())) {
            countByUsername = employeeMapper.selectCountByUsername(employeeDTO.getUsername());
        } else {
            // 排除我
            countByUsername = employeeMapper.selectCountByUsernameAndNotId(employeeDTO.getUsername(), employeeDTO.getId());
        }
        if (countByUsername > 0) {
            throw new AccountExistException("账号重复，请调整");
        }
        // 请输入正确的手机号 11位
        if (Objects.isNull(employeeDTO.getPhone()) ||
                employeeDTO.getPhone().length() != 11) {
            throw new PhoneFormatException("请输入正确的手机号");
        }
        // 身份证号码不正确 18位
        if (Objects.isNull(employeeDTO.getIdNumber()) ||
                employeeDTO.getIdNumber().length() != 18) {
            throw new IdNumberFormatException("身份证号码不正确");
        }
    }

}
